import { MsgFmt } from '../config';
import * as FileIcon from '../assets/file-icon';
import type { GroupRes } from '../http/chatting-group';

// 根据文件路径获取文件类型（用于消息记录）
export const getFileSuffixByPath = (path: string) => {
	const filename = new URLSearchParams(path.split('?')[1]).get('filename');
	const fileSuffix = filename!.substring(filename!.lastIndexOf('.') + 1).toLowerCase();
	switch (fileSuffix) {
		case 'avi':
		case 'mpeg':
		case 'wmv':
		case 'mov':
		case 'flv':
		case 'mp4':
			return 'video';
		case 'png':
		case 'jpeg':
		case 'jpg':
		case 'gif':
		case 'webp':
		case 'svg':
			return 'image';
		default:
			return fileSuffix;
	}
};

// 根据文件名获取文件类型（用于发送消息）
export const getFileSuffixByName = (filename: string) => {
	const fileSuffix = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
	switch (fileSuffix) {
		case 'avi':
		case 'mpeg':
		case 'wmv':
		case 'mov':
		case 'flv':
		case 'mp4':
			return 'video';
		case 'png':
		case 'jpeg':
		case 'jpg':
		case 'gif':
		case 'webp':
		case 'svg':
			return 'image';
		default:
			return 'file';
	}
};

// 获取各类文件图标
export const getFileIcons = (path: string) => {
	const fileSuffix = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
	switch (fileSuffix) {
		case 'docx':
		case 'doc':
			return FileIcon.doc;
		case 'xls':
		case 'xlsx':
			return FileIcon.xls;
		case 'ppt':
		case 'pptx':
			return FileIcon.ppt;
		case 'pdf':
			return FileIcon.pdf;
		case 'apk':
			return FileIcon.apk;
		case 'exe':
			return FileIcon.exe;
		case 'rar':
		case 'zip':
		case 'gz':
		case 'tar':
		case '7z':
			return FileIcon.zip;
		case 'avi':
		case 'mpeg':
		case 'wmv':
		case 'mov':
		case 'flv':
		case 'mp4':
			return FileIcon.mp4;
		case 'txt':
			return FileIcon.txt;
		default:
			return FileIcon.unknown;
	}
};

// 获取文件名
export const getFileName = (path: string) => path.split('/').pop();

// 获取文件后缀
export const getFileExt = (path: string) => path.split('.').pop();

// 根据图片/视频链接获得图片/视频宽高
export const getMediaSize = (
	mediaUrl: string,
	mediaType: string
): Promise<{ width: number; height: number }> => {
	return new Promise((resolve, reject) => {
		if (mediaType === 'image') {
			const mediaElement = document.createElement('img');
			mediaElement.src = mediaUrl;
			mediaElement.onload = () => {
				resolve({ width: mediaElement.width, height: mediaElement.height });
			};
			mediaElement.onerror = () => {
				reject(new Error('图片加载失败'));
			};
		} else if (mediaType === 'video') {
			const mediaElement = document.createElement('video');
			mediaElement.src = mediaUrl;
			mediaElement.addEventListener('canplay', () => {
				resolve({ width: mediaElement.videoWidth, height: mediaElement.videoHeight });
			});
		}
	});
};

// 根据实际宽高计算展示的合理宽高 (图片是按照一定算法缩小，视频是存在横屏和竖屏两种情况)
export const getMediaShowSize = (
	size: { width: number; height: number },
	mediaType: 'image' | 'video'
): { width: string } => {
	if (mediaType === 'image') {
		const widthRem = size.width / 1000;
		if (widthRem < 1) {
			return { width: `${100}px` };
		} else if (widthRem < 3) {
			return { width: `${120}px` };
		} else {
			return { width: `${300}px` };
		}
	} else {
		// 横屏
		if (size.width > size.height) {
			return { width: `${250}px` };
		} else {
			return { width: `${100}px` };
		}
	}
};

// 文件下载
export const downloadFile = (url: string, name = '') => {
	try {
		const x = new window.XMLHttpRequest();
		x.open('GET', url, true);
		x.responseType = 'blob';
		x.onload = () => {
			const url = window.URL.createObjectURL(x.response);
			const link = document.createElement('a');
			link.href = url;
			link.download = name;
			link.click();
		};
		x.send();
	} catch {
		return;
	}
};

// 判断某个文件是否存在（浏览器会发起一个预检请求）
export const urlExists = async (url: string) => {
	try {
		const response = await fetch(url, { method: 'HEAD' });
		return response.ok;
	} catch {
		return false;
	}
};

// 文件大小单位转换
export const byteConvert = (
	bytes: number,
	unit?: string,
	option: { withUnit?: boolean; places?: number } = { withUnit: true, places: 2 }
) => {
	if (bytes === undefined || bytes === null || isNaN(bytes)) return '';
	const { withUnit, places } = option;
	if (bytes === 0) return withUnit ? `${bytes} ${unit ?? 'B'}` : 0;
	const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	if (unit) {
		const index = units.indexOf(unit.toUpperCase());
		if (index > 0) {
			const size = (bytes / Math.pow(1024, index)).toFixed(places);
			return withUnit ? `${size} ${unit}` : Number(size);
		} else {
			return withUnit ? `${bytes} B` : bytes;
		}
	} else {
		const i = Math.floor(Math.log(bytes) / Math.log(1024));
		const size = (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : places);
		return withUnit ? `${size} ${units[i]}` : size;
	}
};

// 获取上传文件与接口字段（msgFmt）对应的类型
export const getFileMsgFmt = (ext: string) => {
	switch (ext) {
		case 'docx':
		case 'doc':
		case 'xls':
		case 'xlsx':
		case 'ppt':
		case 'pptx':
		case 'pdf':
		case 'apk':
		case 'exe':
		case 'rar':
		case 'zip':
		case 'gz':
		case 'tar':
		case '7z':
		case 'mp3':
			return MsgFmt.file;
		case 'png':
		case 'jpeg':
		case 'jpg':
		case 'gif':
		case 'webp':
		case 'svg':
			return MsgFmt.image;
		case 'avi':
		case 'mpeg':
		case 'wmv':
		case 'mov':
		case 'flv':
		case 'mp4':
			return MsgFmt.video;
		default:
			return MsgFmt.txt;
	}
};

export const formatLastMsg = (data: GroupRes) => {
	switch (data.latestMsgFmt) {
		case MsgFmt.file:
			return '[文件]';
		case MsgFmt.image:
			return '[图片]';
		case MsgFmt.video:
			return '[视频]';
		default:
			return data.latestMsg;
	}
};
